package com.wenhao.leetcode.medium;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


/**
 * @author Wenhao Tong
 * @date 2021/7/19 下午10:38
 */
public class LeetCode18 {
    public static void main(String[] args) {
        LeetCode18 leetCode18 = new LeetCode18();
        List<List<Integer>> lists = leetCode18.fourSum(new int[]{1, 0, -1, 0, -2, 2}, 0);
        System.out.println(lists);
    }
    public List<List<Integer>> fourSum(int[] nums, int target) {
        Arrays.sort(nums);
        List<List<Integer>> result = new ArrayList<>();
        for (int i = 0;i < nums.length;i++) {
            if (i > 0 && nums[i] == nums[i - 1]) {
                continue;
            }
            for (int j = i + 1;j < nums.length;j++) {
                if (nums[j] == nums[j - 1]) {
                    continue;
                }
                for (int k = j + 1;k < nums.length;k++) {
                    if (nums[k] == nums[k - 1]) {
                        continue;
                    }
                    int lo = k + 1;
                    int hi = nums.length;
                    int mid;
                    int temp = target - nums[i] - nums[j] - nums[k];
                    while (lo < hi) {
                        mid = lo + (hi - lo) / 2;
                        if (nums[mid] == temp) {
                            List<Integer> list = new ArrayList<>();
                            list.add(nums[i]);
                            list.add(nums[j]);
                            list.add(nums[k]);
                            list.add(nums[mid]);
                            result.add(list);
                            hi = lo;
                        }
                        if (temp < nums[mid]) {
                            hi = mid;
                        }
                        if (nums[mid] < temp) {
                            lo = mid + 1;
                        }
                    }
                }
            }
        }
        return result;
    }
}
